package api

import (
    "bytes"
    "errors"
    "fmt"
    "github.com/tidwall/gjson"
    "github.com/valyala/fasthttp"
    "hitme/go-api/modules/logger"
    "hitme/go-api/modules/utils"
    "io/ioutil"
    "mime/multipart"
    "net/http"
    "strconv"
)

const(
    idCardUrl = "https://api.zheyings.cn/"
    appKey    = "ytZd6Q2kDNeDTkutY896y-k0BYoEXXn6"
)

type idcardApi struct{}

var IdcardApi = new(idcardApi)

type IdcardRequestForm struct {
    Method string
    Url    string
    Params map[string]string
    Resp   interface{}
}

func (r *idcardApi) PostWithFormData(dto *IdcardRequestForm) error {
    body := new(bytes.Buffer)
    w := multipart.NewWriter(body)
    dto.Params["key"] = appKey
    for k,v :=  range dto.Params {
        w.WriteField(k, v)
    }
    w.Close()
    url := idCardUrl + dto.Url
    req, _ := http.NewRequest(dto.Method, url, body)
    req.Header.Set("Content-Type", w.FormDataContentType())
    resp, _ := http.DefaultClient.Do(req)
    data, _ := ioutil.ReadAll(resp.Body)
    resp.Body.Close()
    fmt.Println(resp.StatusCode)
    fmt.Printf("%s", data)

    // 增加日志
    logger.Info("请求证件照接口【" + dto.Url + "】，入参：" + utils.JsonMarshal(dto.Params) + "，请求结果：" + string(data))

    if resp.StatusCode >= fasthttp.StatusBadRequest {
        return errors.New(gjson.Get(string(data), "msg").String())
    }

    if dto.Resp != nil {
        utils.JsonUnmarshal(string(data), dto.Resp)
    }

    return nil
}

// GetList 证件照规格列表
func (r *idcardApi) GetList() (*IdcardGetListResponse, error) {
    var resp = new(IdcardGetListResponse)
    dto := &IdcardRequestForm{
        Method: "POST",
        Url:    "item/list",
        Resp:   resp,
    }
    err := r.PostWithFormData(dto)
    return resp, err
}

// GetSpecDetail 证件照规格详情
func (r *idcardApi) GetSpecDetail(req IdcardDetailRequest) (*IdcardGetListResponse, error) {
    var resp = new(IdcardGetListResponse)
    postData := make(map[string]string)
    postData["item_id"] = req.ItemId
    dto := &IdcardRequestForm{
        Method: "POST",
        Url:    "item/get",
        Resp:   resp,
        Params: postData,
    }
    err := r.PostWithFormData(dto)
    return resp, err
}

// EnvMake 证件照检测+制作(无水印)
func (r *idcardApi) EnvMake(req IdcardEnvMakeRequest) (*IdcardEnvMakeResponse, error) {
    var resp = new(IdcardEnvMakeResponse)
    postData := make(map[string]string)
    postData["item_id"] = req.ItemId
    postData["image"] = req.Image
    postData["color"] = req.Color
    postData["beauty"] = req.Beauty
    dto := &IdcardRequestForm{
        Method: "POST",
        Url:    "idcardv3/all",
        Resp:   resp,
        Params: postData,
    }
    err := r.PostWithFormData(dto)
    return resp, err
}

// ChangeCloth 证件照换装(无水印)
func (r *idcardApi) ChangeCloth(req IdcardChangeClothRequest) (*IdcardChangeClothResponse, error) {
    var resp = new(IdcardChangeClothResponse)
    postData := make(map[string]string)
    postData["pic_id"] = strconv.Itoa(int(req.PicId))
    postData["color"] = req.Color
    postData["clothes"] = req.Clothes
    dto := &IdcardRequestForm{
        Method: "POST",
        Url:    "idcardv3/clothes",
        Resp:   resp,
        Params: postData,
    }
    err := r.PostWithFormData(dto)
    return resp, err
}

// EnvMakeWm 证件照检测+制作（有水印）
func (r *idcardApi) EnvMakeWm(req IdcardEnvMakeWmRequest) (*IdcardEnvMakeWmResponse, error) {
    var resp = new(IdcardEnvMakeWmResponse)
    postData := make(map[string]string)
    postData["item_id"] = req.ItemId
    postData["image"] = req.Image
    postData["colors"] = req.Color
    postData["beauty"] = req.Beauty
    dto := &IdcardRequestForm{
        Method: "POST",
        Url:    "idcardv5/make",
        Resp:   resp,
        Params: postData,
    }
    err := r.PostWithFormData(dto)
    return resp, err
}

// ChangeClothWm 证件照换装（有水印）
func (r *idcardApi) ChangeClothWm(req IdcardChangeClothWmRequest) (*IdcardChangeClothWmResponse, error) {
    var resp = new(IdcardChangeClothWmResponse)
    postData := make(map[string]string)
    postData["pic_id"] = strconv.Itoa(int(req.PicId))
    postData["color"] = req.Color
    postData["clothes"] = req.Clothes
    dto := &IdcardRequestForm{
        Method: "POST",
        Url:    "idcardv5/clothes",
        Resp:   resp,
        Params: postData,
    }
    err := r.PostWithFormData(dto)
    return resp, err
}